package com.lidroid.xutils.db.sqlite;

import ohos.data.resultset.ResultSet;
import com.lidroid.xutils.db.table.Column;
import com.lidroid.xutils.db.table.DbModel;
import com.lidroid.xutils.db.table.Table;

public class CursorUtils {

    @SuppressWarnings("unchecked")
    public static <T> T getEntity(ResultSet cursor, Class<T> entityType) {
        try {
            if (cursor != null) {
                int columnCount = cursor.getColumnCount();
                Table table = Table.get(entityType);
                T entity = entityType.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    String columnName = cursor.getColumnNameForIndex(i);
                    Column column = table.columnMap.get(columnName);
                    if (column != null) {
                        column.setValue(entity, cursor.getString(i));
                    } else if (columnName.equals(table.getId().getColumnName())) {
                        table.getId().setValue(entity, cursor.getString(i));
                    }
                }
                return entity;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static DbModel getDbModel(ResultSet cursor) {
        DbModel result = null;
        if (cursor != null) {
            result = new DbModel();
            int columnCount = cursor.getColumnCount();
            for (int i = 0; i < columnCount; i++) {
                result.add(cursor.getColumnNameForIndex(i), cursor.getString(i));
            }
        }
        return result;
    }
}
